<template>
    <div class="friend-grouping">
        <!-- 添加分组按钮 -->
        <div class="add-group-btn">
            <van-button icon="plus" type="primary" round size="small" @click="showAddGroupDialog = true">添加分组</van-button>
        </div>

        <!-- 分组列表 -->
        <van-collapse v-model="activeNames" accordion class="custom-collapse">
            <van-collapse-item 
                v-for="(group, index) in groupList" 
                :key="index" 
                :name="group.name"
                class="group-item"
            >
                <template #title>
                    <div class="group-title">
                        <van-icon :name="getGroupIcon(group.name)" class="group-icon" />
                        <span>{{ group.name }}</span>
                        <span class="friend-count">({{ getFriendsInGroup(group.name).length }})</span>
                    </div>
                </template>
                <template #right-icon>
                    <div class="action-buttons">
                        <van-icon name="edit" class="edit-icon" @click.stop="editGroup(group)" />
                        <van-icon name="delete" class="delete-icon" @click.stop="deleteGroup(group)" />
                    </div>
                </template>

                <!-- 分组中的好友列表 -->
                <div class="friend-list">
                    <transition-group name="list">
                        <van-cell 
                            v-for="friend in getFriendsInGroup(group.name)" 
                            :key="friend.friendId._id"
                            :title="getDisplayName(friend)"
                            class="friend-item"
                            @click="goToChat(friend)"
                        >
                            <template #icon>
                                <van-image round fit="cover" width="2.8rem" height="2.8rem" :src="friend.friendId.headImgUrl" class="friend-avatar" />
                            </template>
                            <template #right-icon>
                                <van-dropdown-menu direction="up">
                                    <van-dropdown-item 
                                        v-model="friend.friendGroup" 
                                        :options="groupOptions"
                                        title="选择分组" 
                                        @change="changeGroup(friend, $event)"
                                    >
                                        <template #default>
                                            <van-icon name="arrow" class="move-icon" />
                                        </template>
                                    </van-dropdown-item>
                                </van-dropdown-menu>
                            </template>
                        </van-cell>
                    </transition-group>
                    <van-empty description="暂无好友" v-if="getFriendsInGroup(group.name).length === 0" />
                </div>
            </van-collapse-item>
        </van-collapse>
        <van-empty description="暂无分组" v-if="groupList.length === 0" />

        <!-- 添加分组对话框 -->
        <van-dialog
            v-model="showAddGroupDialog"
            title="添加分组"
            show-cancel-button
            confirm-button-color="#07C160"
            @confirm="addGroup"
            class="custom-dialog"
        >
            <van-field
                v-model="newGroupName"
                placeholder="请输入分组名称"
                :maxlength="10"
                show-word-limit
                class="group-input"
            />
        </van-dialog>

        <!-- 编辑分组对话框 -->
        <van-dialog
            v-model="showEditGroupDialog"
            title="编辑分组"
            show-cancel-button
            confirm-button-color="#07C160"
            @confirm="updateGroup"
            class="custom-dialog"
        >
            <van-field
                v-model="editingGroupName"
                placeholder="请输入新分组名称"
                :maxlength="10"
                show-word-limit
                class="group-input"
            />
        </van-dialog>

        <!-- 确认删除分组对话框 -->
        <van-dialog
            v-model="showDeleteConfirm"
            title="删除分组"
            message="确定要删除此分组吗？分组内的好友将被移动到默认分组。"
            show-cancel-button
            confirm-button-color="#ff4d4f"
            @confirm="confirmDeleteGroup"
            class="custom-dialog"
        />
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
import { Toast } from 'vant';
import socket from '@/socket';

export default {
    data() {
        return {
            activeNames: [],
            showAddGroupDialog: false,
            showEditGroupDialog: false,
            showDeleteConfirm: false,
            newGroupName: '',
            editingGroupName: '',
            editingGroup: null,
            deletingGroup: null,
            // 默认分组
            defaultGroups: [
                { name: '我的好友', default: true },
                { name: '家人', default: false },
                { name: '同学', default: false },
                { name: '同事', default: false }
            ]
        };
    },
    computed: {
        ...mapState(['friendList', 'user']),
        // 所有分组列表
        groupList() {
            // 从本地存储获取用户自定义分组
            const userGroups = JSON.parse(localStorage.getItem(`groups_${this.user.phone}`)) || [];
            
            // 合并默认分组和用户自定义分组
            return [...this.defaultGroups, ...userGroups].filter(group => !group.deleted);
        },
        // 下拉菜单选项
        groupOptions() {
            return this.groupList.map(group => ({
                text: group.name,
                value: group.name
            }));
        }
    },
    methods: {
        ...mapMutations(['upFriend']),
        // 根据分组名获取图标
        getGroupIcon(groupName) {
            const icons = {
                '我的好友': 'friends-o',
                '家人': 'home-o',
                '同学': 'bookmark-o',
                '同事': 'manager-o'
            };
            return icons[groupName] || 'star-o';
        },
        // 获取指定分组中的好友
        getFriendsInGroup(groupName) {
            return this.friendList.filter(friend => 
                // 如果好友没有分组或分组为空，则归为默认分组"我的好友"
                (groupName === '我的好友' && (!friend.friendGroup || friend.friendGroup === '')) || 
                friend.friendGroup === groupName
            );
        },
        // 获取好友显示名称（优先显示备注名）
        getDisplayName(friend) {
            if (friend.remark && friend.remark.trim() !== '') {
                return friend.remark;
            }
            return friend.friendId.nickname;
        },
        // 跳转到聊天界面
        goToChat(friend) {
            this.$router.push({ 
                path: '/chat', 
                query: { user_id: friend.friendId._id } 
            });
        },
        // 添加新分组
        addGroup() {
            if (!this.newGroupName.trim()) {
                Toast.fail('分组名称不能为空');
                return;
            }
            
            // 检查分组名是否已存在
            if (this.groupList.some(group => group.name === this.newGroupName)) {
                Toast.fail('分组名称已存在');
                return;
            }
            
            // 从本地存储获取当前分组列表
            const userGroups = JSON.parse(localStorage.getItem(`groups_${this.user.phone}`)) || [];
            
            // 添加新分组
            userGroups.push({
                name: this.newGroupName,
                default: false,
                deleted: false
            });
            
            // 保存到本地存储
            localStorage.setItem(`groups_${this.user.phone}`, JSON.stringify(userGroups));
            
            // 打开新添加的分组
            this.activeNames = [this.newGroupName];
            
            // 重置表单
            this.newGroupName = '';
            
            Toast({
                message: '添加分组成功',
                icon: 'success',
                className: 'custom-toast'
            });
        },
        // 编辑分组
        editGroup(group) {
            // 默认分组不能编辑
            if (group.default) {
                Toast({
                    message: '默认分组不能编辑',
                    icon: 'cross',
                    className: 'custom-toast'
                });
                return;
            }
            
            this.editingGroup = group;
            this.editingGroupName = group.name;
            this.showEditGroupDialog = true;
        },
        // 更新分组
        updateGroup() {
            if (!this.editingGroupName.trim()) {
                Toast.fail('分组名称不能为空');
                return;
            }
            
            // 检查新名称是否与其他分组名称冲突
            if (this.groupList.some(group => 
                group.name === this.editingGroupName && 
                group.name !== this.editingGroup.name)) {
                Toast.fail('分组名称已存在');
                return;
            }
            
            // 从本地存储获取当前分组列表
            const userGroups = JSON.parse(localStorage.getItem(`groups_${this.user.phone}`)) || [];
            
            // 更新分组名称
            const oldName = this.editingGroup.name;
            const newName = this.editingGroupName;
            
            // 更新用户分组
            const updatedGroups = userGroups.map(group => {
                if (group.name === oldName) {
                    return { ...group, name: newName };
                }
                return group;
            });
            
            // 保存到本地存储
            localStorage.setItem(`groups_${this.user.phone}`, JSON.stringify(updatedGroups));
            
            // 更新好友分组
            this.updateFriendsGroup(oldName, newName);
            
            // 更新激活的分组名称
            const index = this.activeNames.indexOf(oldName);
            if (index !== -1) {
                this.activeNames.splice(index, 1, newName);
            }
            
            Toast({
                message: '修改分组成功',
                icon: 'success',
                className: 'custom-toast'
            });
        },
        // 删除分组
        deleteGroup(group) {
            // 默认分组不能删除
            if (group.default) {
                Toast({
                    message: '默认分组不能删除',
                    icon: 'cross',
                    className: 'custom-toast'
                });
                return;
            }
            
            this.deletingGroup = group;
            this.showDeleteConfirm = true;
        },
        // 确认删除分组
        confirmDeleteGroup() {
            // 从本地存储获取当前分组列表
            const userGroups = JSON.parse(localStorage.getItem(`groups_${this.user.phone}`)) || [];
            
            // 标记分组为已删除或直接删除
            const updatedGroups = userGroups.filter(group => group.name !== this.deletingGroup.name);
            
            // 保存到本地存储
            localStorage.setItem(`groups_${this.user.phone}`, JSON.stringify(updatedGroups));
            
            // 将该分组的好友移动到默认分组
            this.updateFriendsGroup(this.deletingGroup.name, '我的好友');
            
            // 从激活的分组名称中移除
            const index = this.activeNames.indexOf(this.deletingGroup.name);
            if (index !== -1) {
                this.activeNames.splice(index, 1);
            }
            
            Toast({
                message: '删除分组成功',
                icon: 'success',
                className: 'custom-toast'
            });
        },
        // 更新好友分组
        async updateFriendsGroup(oldGroup, newGroup) {
            // 获取需要更新的好友列表
            const friendsToUpdate = this.friendList.filter(friend => friend.friendGroup === oldGroup);
            
            // 没有需要更新的好友，直接返回
            if (friendsToUpdate.length === 0) return;
            
            // 更新本地好友分组
            const updatedFriendList = this.friendList.map(friend => {
                if (friend.friendGroup === oldGroup) {
                    return { ...friend, friendGroup: newGroup };
                }
                return friend;
            });
            
            // 更新状态管理中的好友列表
            this.friendList.splice(0, this.friendList.length);
            this.upFriend(updatedFriendList);
            
            // 更新服务器上的好友分组
            for (const friend of friendsToUpdate) {
                try {
                    await this.updateFriendGroupOnServer(friend.friendId._id, newGroup);
                } catch (error) {
                    console.error('更新好友分组失败:', error);
                    Toast({
                        message: '部分好友分组更新失败',
                        icon: 'warning-o',
                        className: 'custom-toast'
                    });
                }
            }
        },
        // 更新服务器上的好友分组
        updateFriendGroupOnServer(friendId, groupName) {
            return new Promise((resolve, reject) => {
                socket.emit('update_friend_group', {
                    phone: this.user.phone,
                    friendId: friendId,
                    groupName: groupName
                }, response => {
                    if (response.code === 200) {
                        resolve(response);
                    } else {
                        reject(response);
                    }
                });
            });
        },
        // 改变好友所属分组
        async changeGroup(friend, newGroup) {
            try {
                // 更新服务器数据
                await this.updateFriendGroupOnServer(friend.friendId._id, newGroup);
                
                // 更新本地数据
                const index = this.friendList.findIndex(f => f.friendId._id === friend.friendId._id);
                if (index !== -1) {
                    this.$set(this.friendList[index], 'friendGroup', newGroup);
                }
                
                Toast({
                    message: '更新分组成功',
                    icon: 'success',
                    className: 'custom-toast'
                });
            } catch (error) {
                console.error('更新好友分组失败:', error);
                Toast({
                    message: '更新分组失败',
                    icon: 'cross',
                    className: 'custom-toast'
                });
                
                // 回滚UI显示
                friend.friendGroup = friend.friendGroup;
            }
        }
    },
    created() {
        // 初始化，打开第一个分组
        if (this.groupList.length > 0) {
            this.activeNames = [this.groupList[0].name];
        }
    }
};
</script>

<style lang="less" scoped>
.friend-grouping {
    padding: 10px 0;
    
    .add-group-btn {
        display: flex;
        justify-content: flex-end;
        padding: 0 16px 15px;
        
        .van-button {
            box-shadow: 0 2px 8px rgba(7, 193, 96, 0.3);
            font-weight: 500;
        }
    }
    
    .custom-collapse {
        .group-item {
            margin-bottom: 8px;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
            background-color: #fff;
            
            &:last-child {
                margin-bottom: 0;
            }
            
            .van-cell {
                align-items: center;
                transition: background-color 0.3s;
                
                &:active {
                    background-color: #f8f8f8;
                }
            }
        }
    }
    
    .group-title {
        display: flex;
        align-items: center;
        font-size: 15px;
        font-weight: 500;
        
        .group-icon {
            margin-right: 10px;
            font-size: 18px;
            color: #07C160;
        }
        
        .friend-count {
            font-size: 12px;
            color: #999;
            margin-left: 5px;
            font-weight: normal;
        }
    }
    
    .action-buttons {
        display: flex;
        align-items: center;
    }
    
    .edit-icon, .delete-icon {
        margin-left: 15px;
        font-size: 16px;
        padding: 4px;
        border-radius: 50%;
        transition: all 0.3s;
        
        &:active {
            transform: scale(0.9);
        }
    }
    
    .edit-icon {
        color: #2196f3;
        
        &:active {
            background-color: rgba(33, 150, 243, 0.1);
        }
    }
    
    .delete-icon {
        color: #f44336;
        
        &:active {
            background-color: rgba(244, 67, 54, 0.1);
        }
    }
    
    .friend-list {
        padding: 0 5px;
        
        .friend-item {
            margin: 5px 0;
            border-radius: 8px;
            background-color: #f8f8f8;
            transition: all 0.3s;
            
            &:active {
                background-color: #f0f0f0;
            }
            
            .friend-avatar {
                margin-right: 12px;
                border: 2px solid #fff;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }
            
            .move-icon {
                font-size: 16px;
                color: #999;
                padding: 5px;
                border-radius: 50%;
                
                &:active {
                    background-color: rgba(0, 0, 0, 0.05);
                }
            }
        }
    }
    
    // 列表动画
    .list-enter-active, .list-leave-active {
        transition: all 0.5s;
    }
    .list-enter, .list-leave-to {
        opacity: 0;
        transform: translateY(20px);
    }
    
    .custom-dialog {
        .group-input {
            margin: 20px 16px;
            
            :deep(.van-field__control) {
                height: 40px;
            }
        }
    }
}

// 修改全局样式
:deep(.van-dialog__confirm) {
    color: #07C160 !important;
}

:deep(.custom-toast) {
    &.van-toast--success {
        background-color: rgba(7, 193, 96, 0.8);
    }
    
    &.van-toast--fail {
        background-color: rgba(244, 67, 54, 0.8);
    }
}
</style>